<?php
/**
 *
 * UserMoodRecord model class file
 *
 * @category   UC
 * @author     张丽媛 <zhangliyuan@snda.com>
 * @copyright  2010-2010 SDO UC Group
 * @version    Release: 1.0.0
 * @link       http://www.sdo.com
 * @modified   2010-3-31 20:20
 */
require_once(dirname(__FILE__).'/../../config/UCConfMacro.php');
require_once(dirname(__FILE__).'/../../config/UCConfTwitter.php');
require_once(dirname(__FILE__).'/../../libraries/UCLibPDOFactory.php');
require_once(dirname(__FILE__).'/../../libraries/UCLibCache.php');


class UCModUserMoodRecord{
	private $_user_id;
	private $_mkey_mood_list;
	private $_mkey_latest_mood;
	private $_mkey_per_day_tuita_num;
	private $_cache;
	private $_errno;
	private $_included = false;
	private $_at_users = array();


	const USER_TWITTER_PARAMS_ERROR        = -1;
    const USER_TWITTER_INSERT_DB_ERROR     = -2;
	const USER_TWITTER_UPDATE_DB_ERROR     = -3;
	const USER_TWITTER_GETONE_DB_ERROR     = -4;
	const USER_TWITTER_LIST_DB_ERROR       = -5;
	const USER_TWITTER_TOTAL_DB_ERROR      = -6;
	const USER_TWITTER_CONVEYNUM_DB_ERROR  = -7;
	const USER_TWITTER_CONVEYLIST_DB_ERROR = -8;
	const USER_TWITTER_CONVEYTOTAL_DB_ERROR= -9;
	const USER_TWITTER_DB_ERROR            = -10;
	const MAP_TWITTER_INSERT_DB_ERROR      = -11;
	const TWITTER_CONTENT_SENSITIVE_ERROR  = -12;
	const POST_TWITTER_TOO_FAST            = -13;
	const POST_SENSITIVE_IMG_ERROR         = -14;

    static $errorArray = array(
        self::USER_TWITTER_PARAMS_ERROR    =>"Params Error",  
        self::USER_TWITTER_INSERT_DB_ERROR => "Insert User DB Opretion Error",
		self::USER_TWITTER_UPDATE_DB_ERROR =>"Update User DB Opretion Error",  
        self::USER_TWITTER_GETONE_DB_ERROR => "Get One DB Opretion Error",
		self::USER_TWITTER_LIST_DB_ERROR   => "Get List DB Opretion Error",
		self::USER_TWITTER_TOTAL_DB_ERROR  => "Get Total Num DB Opretion Error", 
		self::USER_TWITTER_CONVEYNUM_DB_ERROR =>"Get One Conveynum DB Opretion Error",  
        self::USER_TWITTER_CONVEYLIST_DB_ERROR => "Get Conveylist  DB Opretion Error",
		self::USER_TWITTER_CONVEYTOTAL_DB_ERROR=> "Get ConveyTotal DB Opretion Error",
		self::USER_TWITTER_DB_ERROR            => "User DB Opretion Error",
		self::MAP_TWITTER_INSERT_DB_ERROR      => "Map DB Opretion Error", 
		self::TWITTER_CONTENT_SENSITIVE_ERROR     => "Content is Sensitive Error", 
		self::POST_TWITTER_TOO_FAST			   => "Content is FAST Error", 
		self::POST_SENSITIVE_IMG_ERROR		   => "IMG is Sensitive Error", 
    );


	function __construct($user_id){
		 if( !$this->_included ) {
			require_once(dirname(__FILE__).'/../../libraries/UCLibMISApi.php');//信息审核
			require_once(dirname(__FILE__).'/../user/UCModUserStatistics.php');//用户统计库
			require_once(dirname(__FILE__).'/../user/UCModActiveUser.php');//白名单
			require_once(dirname(__FILE__).'/../message/UCModMessageMgr.php');//系统消息
			require_once(dirname(__FILE__).'/../feed/UCModFeed.php');//动态接口
			require_once(dirname(__FILE__).'/UCModTwitterMap.php');
			require_once(dirname(__FILE__).'/UCModHotMoodRecord.php');//热门记录
			require_once(dirname(__FILE__).'/../store/UCModStore.php');//app
			require_once(dirname(__FILE__).'/../store/UCModPanel.php');//app
			require_once(dirname(__FILE__).'/../comment/UCModComment.php');//评论数


		    $this->_included = true;
		 }

		$this->_user_id = $user_id;
		$this->_mkey_mood_list_1 = UCConfTwitter::getMemUserTwitterPage1Key($user_id);//推他列表第一页缓存
		$this->_mkey_latest_mood = UCConfTwitter::getMemUserLatestTwitterKey($user_id); //最新发表的一条心情记录
		$this->_mkey_per_day_tuita_num = UCConfTwitter::getMemcacheUserTuitaNumPerdayKey($user_id);//每天发表的推他数
		$this->_cache = new UCLibCache(TWITTER_MCACHE_CHANNEL_NAME);
	}

	function __destruct(){
		$this->_cache->close();
	}
    
	/**
	 * @purpose: 统一获取错误信息
     * @return : 错误提示
	 */
	public function getErrorInfo() {
		$error_info = array();
		$error_info['error_no'] = $this->_errno;
		$error_info['error_msg'] = self::$errorArray[$this->_errno];
		return $error_info;
	}

	/**
	 * @purpose: 检测IP是否是有效
     * @return : 错误提示
	 */
	public function IpIsValide($ip){
		$long_ip = ip2long($ip);
		if ($long_ip == -1 || $long_ip === FALSE) {
			return false;
		}
		return $long_ip;
	}

    
   /**
	 * @purpose: 添加心情记录
	 * @params : array( 'content'=>'记录内容',
	 *                  'mood'=>'用户心情状态',
	 *                  'type'=>'心情记录类型: 1 文字，2 图片，3视频',
	 *                  'release_time'=>'发表时间：2009-09-09 00:00:00',
	 *                  'ip'=>'ip地址：10.129.128.13'
	 *                  'tags'=>'记录标签，可以为空',
	 *                  'source_desc'=>'记录来源描述: web,game name,phone 等等', 
	 *            )
     * @return : array -插入的数据 成功,false- 失败
	 */
	function addMoodRecord($input){
		$long_ip = $this->IpIsValide($input['ip']);
		
		if(!is_array($input)||count($input)<1 ||(mb_strlen($input['content'],'utf8')==0 && $input['type'] < 2)||!$long_ip) {
			$this->_errno = self::USER_TWITTER_PARAMS_ERROR;
			return false;
		}
		//undo参数入db前，类型长度的检查
		$data = array(); 
		$data['user_id'] = $this->_user_id;
		$data['content'] = $input['content'];
		$data['mood']    = $input['mood'];
		$data['release_time']=empty($input['release_time'])?date("Y-m-d H:i:s"):$input['release_time'];
		$data['type'] =empty($input['type'])?1:$input['type'];
		$data['tags'] = empty($input['tags'])?'':$input['tags'];
		$data['source_desc'] = empty($input['source_desc'])?'':$input['source_desc'];
		$data['ip'] = $long_ip;
		$data['attachment'] = '';
	    if($data['type'] == 3){//视频
			$temp = array();
			$temp['title']= $input['title'];
			$temp['original_url']= $input['original_url'];
			$temp['contract_url']= $input['contract_url'];
			$data['attachment'] =  serialize($temp);
			unset($temp);
		}else if($data['type'] == 2){//图片，先不序列化图片信息
			$data['title']= $input['title'];
			$data['original_url']= $input['original_url'];
			$data['contract_url']= $input['contract_url'];
		}
		
		//插入记录到user mood db中
		$insert_mood_info = $this -> _insertUserDataIntoDB($data);
		if(!is_array($insert_mood_info)){
			return false;
		}
		$this->_at_users = array();
		
		

        //监控统计
		if($data['type']== 2){//插入图片条数
			UCLibStat::action(UCConfStat::STAT_TWITTER_IMG);
		}else if($data['type']== 3){//插入视频条数
			UCLibStat::action(UCConfStat::STAT_TWITTER_VIDEO);
		}
		
		return $insert_mood_info;	
	}


	/**
	 * @purpose: 转帖某条心情记录
	 * @params : source_user:直接转帖的用户id
	 *           source_mood:直接转帖的mood_id
	 *           input: 转帖人的各项信息
     * @return : array - 插入的新数据 成功, false - 失败
	 */
	function conveyOneMoodRecord($source_mood,$source_user,$input){
		
		$long_ip = $this->IpIsValide($input['ip']);
		if(empty($source_user)||empty($source_mood)||!is_array($input)||count($input)<1||!$long_ip){
			$this->_errno = self::USER_TWITTER_PARAMS_ERROR;
			return false;
		}
		//获取直接转帖的内容
		$userMood = new UCModUserMoodRecord($source_user);
		$ret = $userMood -> getOneRecordByMoodId($source_mood);
		$moodinfo = $ret[0];
		if(false === $moodinfo){
			$this->_err_str = self::USER_TWITTER_GETONE_DB_ERROR ;
			return false;
		}
        
        $data = array(); 
		$data['user_id'] = $this->_user_id;
		$content_length = mb_strlen($input['content'],'utf8');
		$data['content'] = $content_length? $input['content']:'转推';//转帖者发表的内容
		$data['release_time']=empty($input['release_time'])?date("Y-m-d H:i:s"):$input['release_time'];
		$data['tags'] = empty($input['tags'])?'':$input['tags'];
		$data['mood'] = '';
		$data['source_desc'] = empty($input['source_desc'])?'':$input['source_desc'];
		$data['ip'] = $long_ip;
		$data['conveyed_flag'] = 1;
		$data['type'] = $moodinfo['type'];

		if($moodinfo['conveyed_flag']==1){//N次转帖，则获取最原始帖子信息
		    $data['convey_first_mood_id'] = $moodinfo['convey_first_mood_id'];
			$data['convey_first_user_id'] = $moodinfo['convey_first_user_id'];
			$data['convey_first_content'] = $moodinfo['convey_first_content'];
			$data['convey_first_mood'] =    $moodinfo['convey_first_mood'];
			$data['convey_first_release_time'] = $moodinfo['convey_first_release_time'];
			$data['convey_first_type'] = $moodinfo['convey_first_type'];
			$data['convey_first_tags']  = $moodinfo['convey_first_tags'];
			$data['convey_first_source_desc'] = $moodinfo['convey_first_source_desc'];
			$data['convey_first_attachment']  = $moodinfo['convey_first_attachment'];
		}else{//第一次转推
			$data['convey_first_mood_id'] = $moodinfo['mood_id'];
			$data['convey_first_user_id'] = $moodinfo['user_id'];
			$data['convey_first_content'] = utf_substr($moodinfo['content'],300);
			$data['convey_first_mood'] = empty($moodinfo['mood'])?'':$moodinfo['mood'];
			$data['convey_first_release_time'] = $moodinfo['release_time'];
			$data['convey_first_type'] = $moodinfo['type'];
			$data['convey_first_tags']  = $moodinfo['tags'];
			$data['convey_first_source_desc'] = $moodinfo['source_desc'];
			$data['convey_first_attachment']  = $moodinfo['attachment'];
		}
		
		//插入记录到user mood db中
		$insert_mood_info = $this ->_insertUserDataIntoDB($data);
		if(!is_array($insert_mood_info)){
			return false;
		}
        //var_dump($insert_mood_info);
		//更新原帖发表人的转推计数
		if($data['convey_first_user_id'] != $this->_user_id){//自己转推，不进行计数
			$userStatistics = new UCModUserStatistics($data['convey_first_user_id']);
			$userStatistics -> increaseValue(UC_STAT_MOOD_RETWITTER_CNT);
		}
		

		//更新原帖的被转帖次数
		$update = $this -> updateMoodConveyNum($data['convey_first_user_id'],$data['convey_first_mood_id']);
		//var_dump($update);
		
		//更新原帖信息
		$this -> updateOneMoodInfoCache($data['convey_first_user_id'],$data['convey_first_mood_id']);
		$mapinfo = array();
		$mapinfo['source_mood_id']= $data['convey_first_mood_id'];
		$mapinfo['source_user_id']= $data['convey_first_user_id'];
		$mapinfo['convey_mood_id']= $insert_mood_info['mood_id'];
		$mapinfo['convey_user_id']= $data['user_id'];
		$map_ret = $this -> OnTwitterAction('map',$mapinfo);
		//var_dump($mapinfo);
		

		if($moodinfo['conveyed_flag']==1){//如果n次转帖，则还要更新直接转发推他的信息
		   if($moodinfo['user_id'] != $this->_user_id){//自己转推，不进行计数
			 //更新直接转推人的转推计数
			 $userStatistics = new UCModUserStatistics($moodinfo['user_id']);
			 $userStatistics -> increaseValue(UC_STAT_MOOD_RETWITTER_CNT);
		   }

			//更新直接转推被转帖次数
			$update = $this -> updateMoodConveyNum($moodinfo['user_id'],$moodinfo['mood_id']);
			//var_dump($update);
			//更新直接转推信息
			$this -> updateOneMoodInfoCache($moodinfo['user_id'],$moodinfo['mood_id']);
			$mapinfo = array();
			$mapinfo['source_mood_id']= $moodinfo['mood_id'];
			$mapinfo['source_user_id']= $moodinfo['user_id'];
			$mapinfo['convey_mood_id']= $insert_mood_info['mood_id'];
			$mapinfo['convey_user_id']= $data['user_id'];
			$map_ret = $this -> OnTwitterAction('map',$mapinfo);
			//var_dump($mapinfo);
			
			if(empty($this->_at_users)|| !in_array($moodinfo['user_id'],$this->_at_users)){
				//转推成功，给直接转帖的用户发送系统消息
				$num_array = self::_getCommandConveyNum($data);
				$first_comment_num = $num_array['comment_num'];
				$first_conveyed_num = $num_array['conveyed_num'];
				$source_desc = '推他';
				if(!empty($data['source_desc']) && is_numeric($data['source_desc'])){
					$source_desc = self::_getAppNameByAppId($data['source_desc']);
				}
				//var_dump($num_array);
				//var_dump($source_desc);
				//var_dump($data);
				
				$o_mgr = new UCModMessageMgr($data['user_id']);
				$o_mgr->sendNotice(
					'at_twitter_v2',
					$moodinfo['user_id'],
					array(  's_id'=>$data['user_id'],
							'comment'=>$data['content'],
							'ori'=>array('author'=>$data['convey_first_user_id'],
										 'content'=>$data['convey_first_content'],
										 't_id'=>$data['convey_first_mood_id'],
										 'n_com'=>$first_comment_num,
										 'n_copy'=>$first_conveyed_num
							            ),
							't_id'=>$insert_mood_info['mood_id'],
							'from'=>$source_desc,
							
						  )
					);
			}

		}else{
			if( empty($this->_at_users)|| !in_array($data['convey_first_user_id'],$this->_at_users)){
				//转推成功，给原帖用户发送系统消息
				$num_array = self::_getCommandConveyNum($data);
				$first_comment_num = $num_array['comment_num'];
				$first_conveyed_num = $num_array['conveyed_num'];
				$source_desc = '推他';
				if(!empty($data['source_desc']) && is_numeric($data['source_desc'])){
					$source_desc = self::_getAppNameByAppId($data['source_desc']);
				}
				
				$o_mgr = new UCModMessageMgr($data['user_id']);
				
				$o_mgr->sendNotice(
					'at_twitter_v2',
					$data['convey_first_user_id'],
					array('s_id'=>$data['user_id'],
						  'comment'=>$data['content'],
						  'ori'=>array('author'=>$data['convey_first_user_id'],'content'=>$data['convey_first_content'],'t_id'=>$data['convey_first_mood_id'],'n_com'=>$first_comment_num,'n_copy'=>$first_conveyed_num),
					      't_id'=>$insert_mood_info['mood_id'],
					      'from'=>$source_desc
					));
			}
		}

		//统计信息:转推的人数
		UCLibStat::statex(UCConfStat::STAT_TWITTER_RE,$data['user_id']);
		$this->_at_users = array();
		return $insert_mood_info;
	}


	/**
	 * @purpose: 插入用户信息到db中
	 * @params array mood_info:用户信息数组
	 * @params boolean convey_flag:是否转帖 
	 * @params string  conveyed_mood:要转的推他id
	 * @params string conveyed_user:要转的user_id
	 * @return :array  插入的记录详情 
	 */
	private function _insertUserDataIntoDB(&$mood_info){
        $data = $mood_info;
		$pdo = UCLibPDOFactory::getPDO(PDO_USER_TAGNAME,$data['user_id'],'twitter2dbconfig');
		$data['mood_id'] = $pdo -> gen_uuid();//生成全局唯一id
		if($data['conveyed_flag']== 1){//转推，则仅判断文字
			$mis_result = self::_misCheckContent($data);
			if(!$mis_result){
					return false;
			}
		}else{
			if($data['type']== 2){//对图片进行审核过滤，然后再决定是否添加入db中
			
			    if($data['content']!='分享图片'){
					$mis_result = self::_misCheckContent($data);
					if(!$mis_result){
						return false;
					}
				}
				
				//判断图片
				$check_result_img = UCLibMISApi::check($data['user_id'], UC_MIS_CHANNEL_TWITTER_IMAGE, $data['original_url']);
				$reason_img = UCLibMISApi::getReason();
			
				if($check_result_img === UC_MIS_RESULT_BAD){//非法图片
					$this->_errno = self::POST_SENSITIVE_IMG_ERROR;
					return  false;
				}
				if($check_result_img === UC_MIS_RESULT_FREQ_LIMIT){//发表频率过快
				   $this->_errno = self::POST_TWITTER_TOO_FAST;
					return  false;
				}
				//图片都要入队列
				UCLibMISApi::add2Q($data['user_id'], UC_MIS_CHANNEL_TWITTER_IMAGE,$data['original_url'],$data['mood_id'], $reason_img);
				
				$temp = array();
				$temp['title']= $data['title'];
				$temp['original_url']= $data['original_url'];
				$temp['contract_url']= $data['contract_url'];
				$data['attachment'] =  serialize($temp);
				unset($data['title']);
				unset($data['original_url']);
				unset($data['contract_url']);
			}else{//视频，文字都只进行文字审核
				$mis_result = self::_misCheckContent($data);
				if(!$mis_result){
					return false;
			   }
			} 
		}

		//审核通过，进行入库操作
		$result  = $pdo -> insert($data);
		
		if(false === $result){
			$this->_errno = self::USER_TWITTER_INSERT_DB_ERROR;
			//var_dump($pdo ->errorInfo());
			return false;
		}
		$insert_data = $data; //记录下插入的记录，以便返回
		//var_dump($insert_data);

		
		//更新用户总的推他数统计信息
		$userStatistics = new UCModUserStatistics($data['user_id']);
		$userStatistics -> increaseValue(UC_STAT_MOOD_CNT);
		//更新用户勋章推他数统计信息
		self::_updateUserMedalStatisticNum($data['user_id']);

        
		//发表或者转推记录入动态。。。。
		$this ->_addTwitterIntoFeed($data);

		//更新发表人的推他列表首页缓存
		$this -> updateMoodListPage1Cache($data);
		
		//更新最新一条推他缓存,为了和db中返回的结果保持一致
		$cache_new = array();
		$cache_new[]= $data;
		$this->_cache->write($this->_mkey_latest_mood,$cache_new, TWITTER_MCACHE_EXPIRE_TIME);
		$this->_cache->close();	

		
		//给@用户发送系统消息
		self::_noticeTagUserMsg($data);

		//添加统计信息
		UCLibStat::action(UCConfStat::STAT_TWITTER);//新增推他数
		UCLibStat::statex(UCConfStat::STAT_TWITTER_USER,$data['user_id']);//新增推他人数
		

		//判断当前用户是否是白名单用户，如果是，则把该条记录发送到热门推他库
		$is_active_user = UCModActiveUser::whetherActiveUser($data['user_id']);
		if($is_active_user){
			$add_time = date("Y-m-d H:i:s");
			$data['add_time'] = $add_time;
			$hotMoodRecord = new UCModHotMoodRecord();
			$res = $hotMoodRecord-> addOneHotMood($data);
		}

		return $insert_data;
	}

	//文字进行审核
	private function _misCheckContent($data){
		$content = $data['content'];
		if(($data['type'] == 3 && $data['content']=='分享视频') ||
			($data['conveyed_flag']== 1 && $data['content']=='转推')){//分享视频 或者转推，仅进行ip审核
			$content = '';
			//$content = $data['content']."  @|__videoinfo__|@  ".$data['attachment'];
		}
		
		
		//对内容进行审核过滤，然后再决定是否添加入db中
		$check_result = UCLibMISApi::check($data['user_id'], UC_MIS_CHANNEL_TWITTER, $content, $data['mood_id']);
	   
		if($check_result === UC_MIS_RESULT_BAD){//强过滤词，不能入库
			$this->_errno = self::TWITTER_CONTENT_SENSITIVE_ERROR;
			return  false;
		}
		if($check_result === UC_MIS_RESULT_FREQ_LIMIT){//发表频率过快
			$this->_errno = self::POST_TWITTER_TOO_FAST;
			return  false;
		}
		if($check_result_words== UC_MIS_RESULT_QUEUE){//入审核队列
			$reason_words = UCLibMISApi::getReason();
			UCLibMISApi::add2Q($data['user_id'], UC_MIS_CHANNEL_TWITTER,$content,$data['mood_id'], $reason_words);
		}
		return true;
	}


	
	//根据@user_name，发送系统通知
	private function _noticeTagUserMsg($data){
		require_once(dirname(__FILE__).'/../user/UCModUserInfo.php');
		//昵称截取
		$content = $data['content'];
		//preg_match_all('/@[\x{4e00}-\x{9fa5}A-Za-z0-9_]+/u',$content,$matches,PREG_PATTERN_ORDER);

		preg_match_all('/@[^`~·～！\!@#￥\$%……\^\&\*\(\)（）\-——\+=\{\}\[\]『』【】\|\\、;；:\：“‘\'\"<>《》,\.，。\/\?？  ]+/u',$content,$matches,PREG_PATTERN_ORDER);
		$source_desc = '推他';
		if(!empty($data['source_desc']) && is_numeric($data['source_desc'])){
			$source_desc = self::_getAppNameByAppId($data['source_desc']);
		}
		
		if(is_array($matches[0])&& count($matches[0])> 0){
			foreach($matches[0] as $key=> $value){
				 $user_nick_name = substr($value,1);
				 //根据昵称转换为连接地址
				 $user_id = UCModUserInfo::getSdidByName($user_nick_name);
				 if($user_id !=false && $user_id !=0){
					  if(in_array($user_id,$this->_at_users)){//已经处理过,下一个
					     continue;
					  }
					 //给@用户发送系统消息
					 $o_mgr = new UCModMessageMgr($data['user_id']);
					 if($data['conveyed_flag']==1){//转推，获取原推的评论和转推数
						$num_array = self::_getCommandConveyNum($data);
						$first_comment_num = $num_array['comment_num'];
						$first_conveyed_num = $num_array['conveyed_num']+1;
						 
						$o_mgr->sendNotice(
							'at_twitter_v2',
							$user_id,
							array('s_id'=>$data['user_id'],
							      'comment'=>$data['content'],
							      'ori'=>array('author'=>$data['convey_first_user_id'],'content'=>$data['convey_first_content'],'t_id'=>$data['convey_first_mood_id'],'n_com'=>$first_comment_num,'n_copy'=>$first_conveyed_num),
								  't_id'=>$data['mood_id'],
							      'from'=>$source_desc)
							);
						
					 }else{//发表推他
						$o_mgr->sendNotice('at_twitter_v2',$user_id,array('s_id'=>$data['user_id'],'comment'=>$data['content'],'ori'=>array(),'t_id'=>$data['mood_id'],'from'=>$source_desc));
					 }
					 array_push($this->_at_users,$user_id);
				 }
			}
		}
		return;
	}

	//获取转帖数和评论数
	private function _getCommandConveyNum($data){
        $result = array();
		$comment_obj = new UCModComment('twitter');
		$comment_num = $comment_obj->amountComment('twitter',$data['convey_first_mood_id']);
		$result['comment_num'] = empty($comment_num)?0:$comment_num;

		$userMood = new UCModUserMoodRecord($data['convey_first_user_id']);
		$mood_res = $userMood -> getOneRecordByMoodId($data['convey_first_mood_id']);
		
		if(false != $mood_res && is_array($mood_res)&& count($mood_res)>0){
			$conveyed_num = $mood_res[0]['conveyed_number'];
		}
		$result['conveyed_num'] = empty($conveyed_num)?0:$conveyed_num;
		
		
		return $result;
	}


	//根据游戏appid 获取游戏名
	private function _getAppNameByAppId($appid){
		Yii::import('sdk_ucmodel.store.UCModStore'); //游戏信息
		$app_desc = '';
		$app_info = UCModStore::getInstance()->getApp($appid);
		if(is_array($app_info) && count($app_info) >0){
			$app_desc = $app_info["title"];
		}
		return $app_desc;
	}


	
	/**
	 * @purpose: 推他信息入动态中
	 * @params array  data: 推他的信息数组
	 * @return :true or false
	 */
	private function _addTwitterIntoFeed($data){
		$feedobj = new UCModFeed($data['user_id']);
		$feed_info = array();
		$feed_info['sdid'] = $data['user_id'];
		$feed_info['reviewable'] = true;
		$feed_info['objectId'] = $data['mood_id'];
		$feed_info['content'] = $data['content'];
		$feed_info['source'] = empty($data['source_desc'])?0:$data['source_desc'];
		if($data['conveyed_flag'] == 1){//转推
		    $feed_info['activityType'] = UCConfFeed::FEED_TYPE_CONVEY_TWITTER;
			$feed_info['originalObjectId'] = $data['convey_first_mood_id'];
			$feed_info['originalAuthorSdid'] = $data['convey_first_user_id'];
			$feed_info['originalContent'] = $data['convey_first_content'];
			$feed_info['originalMood'] = $data['convey_first_mood'];
			$feed_info['originalCreateTime'] = $data['convey_first_release_time'];
			$feed_info['originalType'] = $data['convey_first_type'];
			$feed_info['originalTags'] = $data['convey_first_tags'];
			$feed_info['originalSource'] = empty($data['convey_first_source_desc'])?0:$data['convey_first_source_desc'];
			if(!empty($data['convey_first_attachment'])){
				$temp = unserialize($data['convey_first_attachment']);
				$feed_info['originalPicTitle'] = $temp['title'];
				$feed_info['originalPicUrl'] =   $temp['original_url'];
				$feed_info['originalPriewPicUrl'] = $temp['contract_url'];
			}
		}else{
			
			$feed_info['mood'] = $data['mood'];
		    $feed_info['tags'] = $data['tags'];
			if($data['type'] == 1){//文字
			   $feed_info['activityType'] = UCConfFeed::FEED_TYPE_POST_TWITTER;	
		    }else if($data['type'] == 2 || $data['type'] == 3){//图片或者视频
				if($data['type'] == 2){
					$feed_info['activityType'] = UCConfFeed::FEED_TYPE_IMG_TWITTER;	
				}else{
					$feed_info['activityType'] = UCConfFeed::FEED_TYPE_VIDEO_TWITTER;
				}	
				if(!empty($data['attachment'])){
					$temp = unserialize($data['attachment']);
					$feed_info['pictureTitle'] = $temp['title'];
					$feed_info['pictureUrl'] = $temp['original_url'];
					$feed_info['previewPictureUrl'] = $temp['contract_url'];
				}
		  }
		}
		//var_dump($feed_info);
		$ret = $feedobj -> addOneFeed($feed_info);
		//var_dump('feed:',$ret);
		//var_dump($feedobj ->getErrorMsg());
		return $ret;
	}

  
	/**
	 * @purpose: 更新用户统计库推他信息
	 * @params string  user_id : 用户名
	 * @return :true or false
	 */
	private function _updateUserMedalStatisticNum($user_id){
		$userStatistics = new UCModUserStatistics($user_id);
		$per_day_num = $this->_cache->read($this->_mkey_per_day_tuita_num);
		$this->_cache->close();

		if (false === $per_day_num){
			$this->_cache->write($this->_mkey_per_day_tuita_num,1,PERDAY_TUITA_EXPIRE_TIME);
			$this->_cache->close();	
            
			$medal_tuita_num = $userStatistics -> getValue(UC_STAT_MOOD_MEDAL_CNT); //读取勋章推他统计数，每天一次
			if( $medal_tuita_num == 0){//初始化
			  //设置勋章推他数 = 推他总数;
			   $tuita_total_num = $userStatistics -> getValue(UC_STAT_MOOD_CNT);  
			   $userStatistics -> setValue(UC_STAT_MOOD_MEDAL_CNT,$tuita_total_num);
			}else{//默认加1
			   //改变用户库统计值
			   $userStatistics -> increaseValue(UC_STAT_MOOD_MEDAL_CNT);
			}
		}else if($per_day_num <= PERDAY_TUITA_MAX_NUM){//单天没有超过最大计数条数
		    $per_day_num = $per_day_num +1;
		    $this->_cache->write($this->_mkey_per_day_tuita_num,$per_day_num,PERDAY_TUITA_EXPIRE_TIME);
			$this->_cache->close();
			//改变用户库统计值，默认加1
			$userStatistics -> increaseValue(UC_STAT_MOOD_MEDAL_CNT);
		}
		return;
	}

	/**
	 * @purpose: 更新某条记录的被转帖次数
	 * @params string  source_user:帖子发表者
	 * @params string  source_mood:帖子id
	 * @return :true or false
	 */
	function updateMoodConveyNum($source_user,$source_mood){
		$pdo = UCLibPDOFactory::getPDO(PDO_USER_TAGNAME,$source_user,'twitter2dbconfig');
		$update  = $pdo->exec_with_prepare("update $pdo->database.$pdo->table set conveyed_number=conveyed_number+1 where user_id=? and mood_id=?",array($source_user,$source_mood));
		
		if($update != 1) {
			$this->_errno =  self::USER_TWITTER_UPDATE_DB_ERROR ;
			return false;
		}
		return true;
	}


	/**
	 * @purpose: 取得最新发表的记录信息
	 * @return array or array()
	 */
	public function getNewestMood() {
		$latest_mood = $this->_cache->read($this->_mkey_latest_mood);
		$this->_cache->close();
		if (false === $latest_mood) {
			$pdo = UCLibPDOFactory::getPDO(PDO_USER_TAGNAME,$this->_user_id,'twitter2dbconfig');
			$ret = $pdo -> query_with_prepare("select * from $pdo->database.$pdo->table where user_id=? and status=0 order by release_time desc limit 1",array($this->_user_id));
			if(false === $ret){
				$this->_errno =  self::USER_TWITTER_DB_ERROR ;
				return false;
			}else if(is_array($ret) && count($ret)> 0){
				$latest_mood = $ret;
				$this->_cache->write($this->_mkey_latest_mood, $ret, TWITTER_MCACHE_EXPIRE_TIME);
			    $this->_cache->close();
			}else{
				$latest_mood = array();
				$this->_cache->write($this->_mkey_latest_mood, $ret, TWITTER_MCACHE_EXPIRE_TIME);
			    $this->_cache->close();
			}
		}
		return $latest_mood;
	}

	
	/**
	 * @purpose:从cache中 取得全部心情记录列表
	 * @params int type:查询的类型：0全部，2 图片，3视频
	 * @params int start:记录起始位置
	 * @params int limit:需要取的记录长度
	 * @params int total:总的数量
	 * @return array or false
	 */
	function getAllMoodRecordList($type,$start=0,$limit=TWITTER_DB_PAGE_SIZE){
		if($start < 0) $start = 0;
		if($start > 0 || $type > 0){ //仅缓存全部类型、首页的推他列表首页信息
			$listinfo = $this -> getDBAllMoodRecordList($type,$start,$limit);
		}else{
			$listinfo= $this->_cache->read($this->_mkey_mood_list_1);
			$this->_cache->close();
			if(!is_array($listinfo)){  
				$listinfo = $this -> getDBAllMoodRecordList($type,$start,$limit);
				if (is_array($listinfo)) {
				   $this->_cache->write($this->_mkey_mood_list_1, $listinfo, TWITTER_MCACHE_EXPIRE_TIME);
				   $this->_cache->close();
				} 
			}	
		}
		return $listinfo;
	}
 

	/**
	 * @purpose: 从db中按页取得心情记录列表
	 * @params int type:查询的类型：0全部，2 图片，3视频
	 * @params int start:记录起始位置
	 * @params int limit:需要取的记录长度
	 * @return array or false
	 */
	function getDBAllMoodRecordList($type,$start,$limit){
		$pdo = UCLibPDOFactory::getPDO(PDO_USER_TAGNAME,$this->_user_id,'twitter2dbconfig');
		if($type > 0){
			$list  = $pdo -> query_with_prepare("select * from $pdo->database.$pdo->table where user_id=? and type=? and status=0 order by release_time desc limit ?,?",array($this->_user_id,$type,$start,$limit));
		}else{
			$list  = $pdo -> query_with_prepare("select * from $pdo->database.$pdo->table where user_id=? and status=0 order by release_time desc limit ?,?",array($this->_user_id,$start,$limit));
		}
        if(false === $list){
			$this->_errno =  self::USER_TWITTER_LIST_DB_ERROR ;
			return false;
		}else if(!is_array($list)){ //没有记录，则置为空数组
			$list = array();
		}
		return $list;
	}

	/**
	 * @purpose: 取得当前用户的全部心情记录总数
	 * @params int type:查询的类型：0全部，2 图片，3视频
	 * @return  int  次数
	 */
	 function  getDBAllMoodCount($type){
		if($type > 0){
			$type_str =" and type=? ";
			$value = array($this->_user_id,$type);
		}else{
			$type_str ="";
			$value = array($this->_user_id);
		}
		$pdo = UCLibPDOFactory::getPDO(PDO_USER_TAGNAME,$this->_user_id,'twitter2dbconfig');
		$total_num = $pdo -> query_one_with_prepare("select count(1) as num from $pdo->database.$pdo->table where user_id=? and status=0 ".$type_str,$value);
		if(false === $total_num){
			$this->_errno = self::USER_TWITTER_TOTAL_DB_ERROR ;
			return false;
		}
		return $total_num;
	 }


	/**
	 * @purpose: 从cache读单条心情记录详情
	 * @params string user:用户id
	 * @params string mood_id:记录id
	 * @return :array 成功，false 失败
	 */
	function getOneRecordByMoodId($mood_id){
		if(empty($mood_id)){
			$this->_errno = self::USER_TWITTER_PARAMS_ERROR;
			return false;
		}
		$one_twitter_key = UCConfTwitter::getMemOneTwitterInfoKey($mood_id,$this->_user_id);
		$mood_info  = $this->_cache->read($one_twitter_key);
		if(false === $mood_info){
			$mood_info  = $this -> getDBOneRecordByMoodId($mood_id);
			if(false === $mood_info){
				$this->_errno = self::USER_TWITTER_GETONE_DB_ERROR;
				return false;
			}else{
				$this->_cache->write($one_twitter_key, $mood_info, TWITTER_MCACHE_EXPIRE_TIME);
				$this->_cache->close();
			}
		}
		return $mood_info;
	 }
	

	/**
	 * @purpose: 读单条心情记录被转帖总次数
	 * @params string user:用户id
	 * @params string mood_id:记录id
	 * @return : false：不存在该条记录，成功：int整数
	 */
	function getDBOneRecordByMoodId($mood_id){
		$pdo = UCLibPDOFactory::getPDO(PDO_USER_TAGNAME,$this->_user_id,'twitter2dbconfig');
		$mood_info  = $pdo -> query_with_prepare("select * from $pdo->database.$pdo->table where user_id=? and mood_id=? ",array($this->_user_id,$mood_id));
		return $mood_info;
	}

	/**
	 * @purpose: 从cache中 获取当前用户转推的记录列表
	 * @params int start:记录起始位置
	 * @params int limit:需要取的记录长度
	 * @return array or false
	 */
	function getAllConveyList($start=0,$limit=TWITTER_DB_PAGE_SIZE){
		if($start < 0) $start = 0;
		if($start == 0){
		    $listinfo= $this->_cache->read($this->_mkey_convy_mood_list_1);
			$this->_cache->close();
			if(false === $listinfo){  
				$listinfo = $this->getDBConveyList($start,$limit);
                if (is_array($listinfo)) {
				   $this->_cache->write($this->_mkey_convy_mood_list_1, $listinfo, TWITTER_MCACHE_EXPIRE_TIME);
				   $this->_cache->close();
			    } 
			}	
		}else{
			$listinfo = $this->getDBConveyList($start,$limit);
		}
		return $listinfo;
	}

	/**
	 * @purpose: 从db中按页取得当前用户转发的心情记录列表
	 * @params int start:记录起始位置
	 * @params int limit:需要取的记录长度
	 * @return array or false 
	 */
	function getDBConveyList($start,$limit){
		$pdo = UCLibPDOFactory::getPDO(PDO_USER_TAGNAME,$this->_user_id,'twitter2dbconfig');
		$list  = $pdo->query_with_prepare("select * from $pdo->database.$pdo->table where user_id=? and conveyed_flag=1 and status=0 order by release_time desc limit ?,?",array($this->_user_id,$start,$limit));
        if(false === $list) {
			$this->_errno = self::USER_TWITTER_CONVEYLIST_DB_ERROR ;
			return false;
		}
		return $list;
	}
	
	/**
	 * @purpose: 取得当前用户的转推记录总数
	 * @return  int  次数
	 */
	 function  getDBAllConveyCount(){
		$pdo = UCLibPDOFactory::getPDO(PDO_USER_TAGNAME,$this->_user_id,'twitter2dbconfig');
		$total_arr = $pdo->query_one_row_with_prepare("select count(1) as num from $pdo->database.$pdo->table where user_id=? and conveyed_flag =1 and status=0",array($this->_user_id));
		if(false === $total_arr){
			$this->_errno = self::USER_TWITTER_CONVEYTOTAL_DB_ERROR ;
			return false;
		}else{
			$total = $total_arr['num'];
		} 
		return $total;
	 }

	 /**
	 * @purpose: 定义推他中触发条件满足时的操作函数
	 * @params string action:触发条件:map-转帖时插入映射表，img-插入图片表，video-视频入库
	 * @params array data:插入的数据
	 * @return true or false
	 */
	 function OnTwitterAction($action,$data){
		 if($action == 'map'){//记录转帖人到推他映射表中
			$map = new UCModTwitterMap($data['source_mood_id']);
			$map_ret = $map ->insertIntoTwitterMapDB($data['source_user_id'],$data['convey_mood_id'],$data['convey_user_id']);
			return $map_ret;
		 }
	 }

	 /**
	 * @purpose: 更新某人推他首页缓存
	 */
      function  updateMoodListPage1Cache($data){
		  $oldlistinfo = $this->_cache->read($this->_mkey_mood_list_1);
		  $this->_cache->close();
		  $listinfo = array();
		  if(false === $oldlistinfo){
			  $type = 0;
			  $listinfo = $this -> getDBAllMoodRecordList($type,0,TWITTER_DB_PAGE_SIZE);
		  }else if(is_array($oldlistinfo) && count($oldlistinfo)> 0){
			  if(count($oldlistinfo) >= TWITTER_DB_PAGE_SIZE){
			     array_pop($oldlistinfo);//移除最旧的记录
			  }
			 array_unshift($oldlistinfo,$data);//把该条记录插入最初位置
			 $listinfo = $oldlistinfo;
			  
		  }else{
			  $listinfo[] = $data;
		  }
		  $this->_cache->write($this->_mkey_mood_list_1, $listinfo, TWITTER_MCACHE_EXPIRE_TIME);
		  $this->_cache->close();
		  return;
	  }

	  /**
	   * @purpose: 更新某条推他信息缓存
	   */
      function  updateOneMoodInfoCache($source_user,$source_mood){
		$pdo = UCLibPDOFactory::getPDO(PDO_USER_TAGNAME,$source_user,'twitter2dbconfig');
		$mood_info  = $pdo -> query_with_prepare("select * from $pdo->database.$pdo->table where user_id=? and mood_id=? ",array($source_user,$source_mood));
		$one_twitter_key = UCConfTwitter::getMemOneTwitterInfoKey($source_mood,$source_user);
		$this->_cache->write($one_twitter_key,$mood_info, TWITTER_MCACHE_EXPIRE_TIME);
		$this->_cache->close();
	  }
 
	/**
	 * @purpose: 修改某条记录的信息
	 * @params string mood_id:记录id
	 * @params array  fields  :需要修改的key=>value值
	 * @return : true or false
	 */
	function updateOneRecordById($mood_id,$fields){
		if(empty($mood_id)){
			$this->_errno = self::USER_TWITTER_PARAMS_ERROR;
			return false;
		}
		$condition = array('mood_id' => $mood_id);
		$pdo = UCLibPDOFactory::getPDO(PDO_USER_TAGNAME,$this->_user_id,'twitter2dbconfig');
		$update  = $pdo -> update($fields,$condition);
		//var_dump($update);
		if($update){
			if($fields['status']== 1){//删除
				//更新用户库统计信息
				$userStatistics = new UCModUserStatistics($this->_user_id);
				$userStatistics -> increaseValue(UC_STAT_MOOD_CNT,-1);
				$userStatistics -> increaseValue(UC_STAT_MOOD_MEDAL_CNT,-1);//勋章规则中推他次数
			}

			//更新某条记录的cache
			$this -> updateOneMoodInfoCache($this->_user_id,$mood_id);

			//更新最新记录
			$latest_mood = $this->_cache->read($this->_mkey_latest_mood);
			if(is_array($latest_mood)&& count($latest_mood)>0){
                $newest_mood = $latest_mood[0];
				if($newest_mood['mood_id'] == $mood_id){
					$this->_cache->delete($this->_mkey_latest_mood);
					$result= $this ->getNewestMood();
					$this->_cache->write($this->_mkey_latest_mood,$result,TWITTER_MCACHE_EXPIRE_TIME);
					$this->_cache->close();
				}
			}
			//更新推他首页cache
			$type = 0;
			$listinfo = $this -> getDBAllMoodRecordList($type,0,TWITTER_DB_PAGE_SIZE);
			$this->_cache->write($this->_mkey_mood_list_1, $listinfo, TWITTER_MCACHE_EXPIRE_TIME);
			$this->_cache->close();

			return true;
		}else{
			$this->_errno = self::USER_TWITTER_UPDATE_DB_ERROR;
			return false;
		}
	}
}



   





